package cn.itbaizhan.tyut.exam.sys.servlets;

import cn.itbaizhan.tyut.exam.model.InfoMgr;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author cengy
 */
public class InfoServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String cmd = request.getParameter("cmd");
        if (cmd.equals("list")) {
            list(request, response);
        } else if (cmd.equals("single")) {
            single(request, response);
        }
    }

    private void single(HttpServletRequest request, HttpServletResponse response) {
        int index = 0;
        try {
            index = Integer.parseInt(request.getParameter("index"));

            int size = InfoMgr.INSTANCE.infoList.size();
            if (size > 0 && index < size) {
                request.setAttribute("info", InfoMgr.INSTANCE.get(index));
                request.getRequestDispatcher("/sys/info/single.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void list(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setAttribute("infoList", InfoMgr.INSTANCE.infoList);
            request.getRequestDispatcher("/sys/info/list.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
